package com.mentalhealthplatform.studentV3.controller;

import ch.qos.logback.classic.Logger;
import com.mentalhealthplatform.appModels.CustomUserDetails;
import com.mentalhealthplatform.appModels.Reply;
import com.mentalhealthplatform.studentV3.service.MessageServiceV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

import static org.slf4j.LoggerFactory.*;

@RestController
@RequestMapping("/api/v3/replies")
public class ReplyController {

    @Autowired
    private MessageServiceV3 messageServiceV3;

    // 教师端 - 回复留言
    @PostMapping("/{messageId}")
    public ResponseEntity<Reply> addReply(@PathVariable Long messageId, @RequestBody Reply reply) {
        // 获取当前登录用户的信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof CustomUserDetails userDetails) {
            String teacherId = String.valueOf(userDetails.getTeacherId());
            reply.setTeacherId(UUID.fromString(String.valueOf(teacherId)));
        }

        // 检查回复内容是否为空
        if (reply.getContent() == null || reply.getContent().isEmpty()) {
            throw new RuntimeException("回复内容不能为空");
        }

        // 设置当前时间为回复时间戳
        reply.setCreatedAt(LocalDateTime.now());

        messageServiceV3.addReplyToMessage(messageId, reply);
        return ResponseEntity.status(201).body(reply);
    }

    private static final Logger logger =(Logger) getLogger(ReplyController.class);
    // 学生端 - 获取特定留言的所有回复
    @GetMapping("/{messageId}")
    public ResponseEntity<List<Reply>> getReplies(@PathVariable Long messageId) {
        List<Reply> replies = messageServiceV3.getRepliesByMessageId(messageId);
        return ResponseEntity.ok(replies);
    }

    // 如果 content 为空，将会抛出 MethodArgumentNotValidException
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        return ResponseEntity.badRequest().body(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }
}
